package cloud.demarcia.yzcrawler.processors;

import cloud.demarcia.yzcrawler.entities.Profile;
import cloud.demarcia.yzcrawler.entities.University;
import cloud.demarcia.yzcrawler.entities.WyEntity;
import cloud.demarcia.yzcrawler.utils.Browser;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component
public class InfoProcessor {

    Document doc;
    University university;

    public List<WyEntity> process(String urlString, University university) {
        this.university = university;
        Browser browser = new Browser();
        doc = browser.browse(urlString);
        browser.close();
        return addInfo();
    }

    private List<WyEntity> addInfo() {
        List<Element> elements = doc.getElementsByClass("zsml-res-items");
        List<WyEntity> resList = new LinkedList<>();
        for (Element element : elements) {
            String s = element.child(0).child(1).text();
            if (filter(s)) {
                resList.add(extractInfo(element));
            }
        }
        return resList;
    }

    //二外日语定制版
    private boolean filter(String s) {
        if (university.getProfile().equals(Profile.SUBJECT_ENGLISH)) return true;
        if (university.getProfile().equals(Profile.MTI_TRANSLATION)) return true;
        return s.contains("日语");
    }

    private WyEntity extractInfo(Element element) {
        WyEntity wyEntity = new WyEntity();
        wyEntity.setCourse0(element.child(0).child(1).text());
        wyEntity.setCourse0Ref(element.child(0).child(1).child(0).text());
        wyEntity.setCourse1(element.child(0).child(2).text());
        wyEntity.setCourse1Ref(element.child(0).child(2).child(0).text());
        wyEntity.setCourse2(element.child(0).child(3).text());
        wyEntity.setCourse2Ref(element.child(0).child(3).child(0).text());
        return wyEntity;
    }
}
